package com.cloud.cmt.usermanage.service.impl;

import com.cloud.cmt.usermanage.constant.EnterpriseConstants;
import com.cloud.cmt.usermanage.dao.EnterpriseDetailDAO;
import com.cloud.cmt.usermanage.dao.EnterpriseUserDAO;
import com.cloud.cmt.usermanage.dao.repository.EnterpriseDetailRepository;
import com.cloud.cmt.usermanage.dao.repository.EnterpriseReferrerRepository;
import com.cloud.cmt.usermanage.service.AccountStatusChangeEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.MessageFormat;

/**
 * 浙江卓锐科技股份有限公司 版权所有 © Copyright 2017<br>
 * 说明: <br>
 * 项目名称: cloud-maintenance <br>
 * 创建日期: 2017年11月24日 09:32 <br>
 * 作者: <a href="6492178@gmail.com">汪萌萌</a>
 */
@Component
public class AccountStatusChangeHandle {
    @Resource
    private EnterpriseDetailRepository enterpriseDetailRepository;
    @Resource
    private EnterpriseReferrerRepository referrerRepository;

    /**
     * Handle account status change.
     *
     * @param accountStatusChangeEvent the account status change event
     */
    @Async
    @EventListener
    public void handleAccountStatusChange(AccountStatusChangeEvent accountStatusChangeEvent) {
        EnterpriseUserDAO userDAO = accountStatusChangeEvent.getUserDAO();
        boolean enableFlag = accountStatusChangeEvent.isEnableFlag();
        sendSms(userDAO, enableFlag);
        logLogs(userDAO, enableFlag);
    }

    private void sendSms(EnterpriseUserDAO userDAO, boolean flag) {
        Long enterpriseId = userDAO.getEnterpriseId();
        String enable = userDAO.getEnable() ? "启用" : "禁用";
        EnterpriseDetailDAO detailDAO = enterpriseDetailRepository.findOne(enterpriseId);
        String phone = referrerRepository.getEmployeeByEnterpriseId(enterpriseId);
        phone = phone == null ? "王哲狗日的手机号" : phone;
        String smsContent = "往手机号{0}发送短信,内容为:您的账号:[{1}]状态已变更为:{2},如有疑问,请咨询电话:{3}";
        smsContent = MessageFormat.format(smsContent, detailDAO.getPhone(), userDAO.getUsername(), flag ? enable : EnterpriseConstants.getAccountStatus(userDAO.getAccountStatus()), phone);
        //TODO 发送时间
        System.out.println(smsContent);
    }

    private void logLogs(EnterpriseUserDAO userDAO, boolean flag) {
        String enable = userDAO.getEnable() ? "启用" : "禁用";
        String logContent = "企业Id为:{0}的状态已变更为:{1},操作人{2}";
        logContent = MessageFormat.format(logContent, userDAO.getEnterpriseId(), flag ? enable : EnterpriseConstants.getAccountStatus(userDAO.getAccountStatus()), "王哲");
        //TODO 记录日志
        System.out.println(logContent);
    }


}
